# -*- coding: utf-8 -*-
from __future__ import absolute_import

"""
将下载的近20年的以julian date计时的modis云掩膜产品按月分离 
"""
import datetime
import os
import glob
import shutil


def split_by_month(data_dir):
    files = []
    files.extend(glob.glob("{}\\*Cloud_Mask_1_clip.hdf".format(data_dir))) #一定是非递归
    for file in files:
        path, filename = os.path.split(file) #分离路径和文件名
        file_date = julian_normal_convert(filename[12:17])
        if file_date.month == 1:
            shutil.copy(file, "{}\\Jan".format(data_dir))
        elif file_date.month == 2:
            shutil.copy(file, "{}\\Feb".format(data_dir))
        elif file_date.month == 3:
            shutil.copy(file, "{}\\March".format(data_dir))
        elif file_date.month == 4:
            shutil.copy(file, "{}\\Apri".format(data_dir))
        elif file_date.month == 5:
            shutil.copy(file, "{}\\May".format(data_dir))
        elif file_date.month == 6:
            shutil.copy(file, "{}\\Jun".format(data_dir))
        elif file_date.month == 7:
            shutil.copy(file, "{}\\July".format(data_dir))
        elif file_date.month == 8:
            shutil.copy(file, "{}\\Aug".format(data_dir))
        elif file_date.month == 9:
            shutil.copy(file, "{}\\Sep".format(data_dir))
        elif file_date.month == 10:
            shutil.copy(file, "{}\\Oct".format(data_dir))
        elif file_date.month == 11:
            shutil.copy(file, "{}\\Nov".format(data_dir))
        elif file_date.month == 12:
            shutil.copy(file, "{}\\Dec".format(data_dir))


def julian_normal_convert(julian_date):
    """
    converter
    :param julian_date ex:18001
    :return python datetime.date object ex:20180101
    """
    normal_date = datetime.datetime.strptime(julian_date, '%y%j').date()
    return normal_date


def clip_by_shp(datadir, shp):
    files = []
    files.extend(glob.glob( "{}\\*.hdf".format(datadir)))
    for file in files:
        cmd = "gdalwarp -cutline {} -crop_to_cutline -s_srs EPSG:4008  -t_srs EPSG:32649 -of netCDF {} {}_clip.hdf".format(shp, file, file[:-4])
        os.system(cmd)
    pass


if __name__ == "__main__":
    # julian_normal_convert('16333')

    _dir = "D:\\data\\modis_terra_cloud_mask\\20years\\cloud_mask_1_python_wget"
    shp = "F:\\data\\modis_terra_cloud_mask\\shapefile\\hainan_24_county.shp"
    clip_by_shp(_dir, shp)

    # _dir = "D:\\data\\modis_terra_cloud_mask\\20years\\cloud_mask_1_python_wget"
    # split_by_month(_dir)
    pass

